<template>
  <div class="page-main">
    <query-page
      ref="pageRef"
      v-model:selectedKeys="selectedKeys"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="formRenderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      :total="total"
      :title="tit"
      :height="'60%'"
      row-selection-type="checkbox"
      @selection-change="selectionChange"
      @query-data="getData"
      @row-click="rowClick"
    >
      <template #container-side>
        <batchBtn
          :btn-list="btnList"
          :other-params="{ activeTab, activeRadio, selectedKeys }"
          type="1"
          @result="clickResult"
        ></batchBtn>
      </template>
      <template #attachment="{ record }">
        <a-popover
          title="查看附件"
          trigger="click"
          :content-style="styleUpload"
        >
          <a-button type="text" @click="handleAttachment(record)"
            >查看附件</a-button
          >
          <template #content>
            <div v-if="attachmentList.length === 0">-</div>
            <div
              v-for="(item, index) in attachmentList"
              :key="index"
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <p style="width: 150px">{{ item.fileName }}</p>
              <div>
                <span
                  style="margin: 0 10px; color: #165dff; cursor: pointer"
                  @click="handleDown(item)"
                  >下载</span
                ><span
                  style="color: red; cursor: pointer"
                  @click="handleDel(item, index)"
                  >删除</span
                >
              </div>
            </div>
          </template>
        </a-popover>
      </template>
    </query-page>
    <div :class="screenClass">
      <table-container
        v-model:columns="columns"
        v-model:is-fullscreen="isFullscreen"
        :loading="isLoading2"
        :all-columns="allColumns"
        @refresh="getDataSheet"
      >
        <standard-table
          ref="table2"
          v-model:selectedKeys="selectedKeys2"
          :component-config="tableComponentConfig"
          :render-config="tableRenderConfig"
          :render-keys="tableRenderKeys2"
          :loading="isLoading2"
          :data="renderData2"
          :total="total2"
          row-selection-type="checkbox"
          :columns="columns"
          @init-columns-end="initColumns"
          @selection-change="selectionChange2"
          @page-change="pageChange"
          @page-size-change="pageSizeChange"
        >
          <template #operate="{ record, rowIndex }">
            <a-button type="text" @click="editSheet(record, rowIndex)"
              >编辑</a-button
            >
          </template>
        </standard-table>
      </table-container>
    </div>
    <contentModel
      v-if="visible"
      :title="'编辑'"
      :mask-closable="false"
      @close="visible = false"
    >
      <template #header-right>
        <a-space>
          <a-button
            v-permission="['procurement:compare-item:update']"
            type="primary"
            @click="putSheet"
            >确定</a-button
          >
          <a-button @click="visible = false">取消</a-button>
        </a-space>
      </template>
      <template #title> 修改 </template>
      <a-form :model="formSheet" layout="vertical" class="edit-form">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item field="compareQty" label="比价数量（采购）">
              <a-input
                v-model="formSheet.compareQty"
                placeholder="请输入比价数量（采购）"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="provisionalSum" label="暂列金额">
              <a-input
                v-model="formSheet.provisionalSum"
                placeholder="请输入暂列金额"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="settlementPrice" label="结算单价">
              <a-input
                v-model="formSheet.settlementPrice"
                placeholder="请输入结算单价"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="finalUnitPrice" label="最终议价单价">
              <a-input
                v-model="formSheet.finalUnitPrice"
                placeholder="请输入最终议价单价"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="dealDate" label="议价日期">
              <a-date-picker
                v-model="formSheet.dealDate"
                placeholder="请输入议价日期"
                value-format="YYYY-MM-DD"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="pmsPredictPrice" label="预估价">
              <a-input
                v-model="formSheet.pmsPredictPrice"
                allow-clear
                placeholder="请输入预估价"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </contentModel>
    <!-- 批量上传 -->
    <!-- 文件导入  -->
    <fileUpload
      v-if="fileValueflag"
      v-model="fileValue"
      :selected-id="attachmentUploadList"
      type="2"
      btn-name="文件上传"
      btn-type="text"
      title="Excel导入"
      accept=".xlsx"
      :max-size="10"
      @restion="fileValueflagfun"
    />
  </div>
</template>

<script lang="ts" setup>
  import {
    ref,
    onMounted,
    watch,
    defineAsyncComponent,
    CSSProperties,
  } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import promiseModal from '@/common/utils/modal-promise';
  import queryPage from '@/common/components/query-page/index.vue';
  import {
    getPlanListForBjd,
    page,
    operation,
    generate,
    sheetReturn,
    approved,
    putCompare,
  } from '@/api/supplier/parity-sheet';
  import {
    getPlanFileListByplanListNo,
    delPlanFile,
  } from '@/api/supplier/selective-quotient';
  import StandardTable from '@/common/components/standard-table/index.vue';
  import lodash from 'lodash';
  import useFullScreen from '@/common/hooks/fullScreen';
  import tableContainer from '@/common/components/table-container/index.vue';
  import {
    formRenderConfig,
    formComponentConfig,
  } from './components/formComp/baseFormConfig';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from './components/tableComp/baseTableConfig';
  import { baseRenderKeys } from './components/baseDatasheet';
  import { getBtnList } from './components/baseBtnparitysheet';
  import fileUpload from './components/file-upload-page/index.vue';
  import { getRowBtnList } from './components/rowBaseparitysheet';
  import batchBtn from './components/batchBtn.vue';

  const contentModel = defineAsyncComponent(
    () => import('@/common/components/content-model/index.vue')
  );
  const { isFullscreen, screenClass } = useFullScreen();
  const tit = ref('比价单生成-按计划');
  const selectedKeys = ref([]);
  const selectedKeys2 = ref([]);
  const activeTab = ref('');
  const activeRadio = ref('');
  const isLoading = ref(true);
  const isLoading2 = ref(false);
  const renderData = ref<any[]>([]);
  const renderData2 = ref<any[]>([]);
  // 渲染检索项
  const formRenderKeys = ref<any[]>([]);
  const tableRenderKeys = ref<any[]>([]);
  const tableRenderKeys2 = ref<any[]>([]);
  const pageRef = ref();
  const planListNoStroage = ref('');
  // 下拉内容数据
  const selsectlist = ref<any[]>([
    { label: '男', value: 1 },
    { label: '女', value: 2 },
  ]);
  const styleUpload =
    'max-height:300px;overflow: auto;' as unknown as CSSProperties;
  const fileValue = ref({});
  const fileValueflag = ref(false);
  const attachmentUploadList = ref<any>([]);
  const attachmentList = ref<any>([]);
  const table2 = ref();
  const total = ref(0);
  formRenderKeys.value =
    baseRenderKeys.comparisonsheetgeneratedAsplanned.formRenderKeys;
  tableRenderKeys.value =
    baseRenderKeys.comparisonsheetgeneratedAsplanned.newTableRenderKeys;
  tableRenderKeys2.value =
    baseRenderKeys.comparisonsheetgeneratedAsplanned.cmTableRenderKeys;
  const btnList = ref<any[]>([]);
  const rowBtnList = ref<any[]>([]);
  const columns = ref<object[]>([]);
  const visible = ref(false);
  const formSheet = ref<any>({});
  const allColumns = ref<object[]>([]);
  const allBtnType = ref('');
  const total2 = ref(0);
  const getData = async (queryInfo: object) => {
    isLoading.value = true;

    try {
      const res: any = await getPlanListForBjd(queryInfo);
      if (res.code === 200) {
        renderData.value = res.data.list;
        total.value = res.data.total;
        console.log(res);
      }
    } catch (err) {
      console.log(err);
    } finally {
      isLoading.value = false;
    }
  };

  const selectionChange = async (val: string[]) => {
    console.log(val);
  };
  const compilechange = (val: any = {}) => {
    if (val.id) {
      selectedKeys.value = [val.id as never];
    }
    attachmentUploadList.value = selectedKeys.value.map((v) => {
      return renderData.value.find((m) => v === m.id).planListNo;
    });

    fileValueflag.value = true;
  };
  const selectionChange2 = async (val: string[]) => {
    console.log(val);
  };
  const fileValueflagfun = (flag: any) => {
    fileValueflag.value = flag;
    selectedKeys.value = [];
  };
  const getDataSheet = () => {};
  // 按钮操作点击事件
  const clickResult = async (
    type: string,
    typeChange: string,
    otherParams: any,
    testval: object
  ) => {
    console.log('type：', type, typeChange, otherParams, testval);
    allBtnType.value = typeChange;
    if (typeChange === 'uploadBatch') {
      compilechange();
    } else if (typeChange === 'autoBudget') {
      if (selectedKeys.value.length !== 1) {
        Message.warning('自动预选请选择一条数据！');
        return;
      }
      try {
        await promiseModal.confirm({
          title: '自动预选',
          content: '您确定对当前所选数据进行自动预选，手动选中标识的除外',
          modalStyle: { wordBreak: 'break-all' },
        });
      } catch (e: any) {
        return;
      }
      const { planListNo } = renderData.value.find(
        (item) => item.id === selectedKeys.value[0]
      );
      const operParam = { planListNo, ...testval };
      try {
        const res: any = await operation(operParam);
        if (res.code === 200) {
          Message.success('预选成功');
          selectedKeys.value = [];
          const params = { planListNo };
          getData2(params);
        } else {
          Message.warning(res.message);
        }
      } catch (err: any) {
        console.log(err);
      } finally {
        isLoading.value = false;
      }
    } else if (typeChange === 'generateSheet') {
      if (selectedKeys.value.length !== 1) {
        Message.warning('请选择要生成比价单的记录！');
        return;
      }
      try {
        await promiseModal.confirm({
          title: '生成比价单',
          content: '您确定要将当前所选的数据生成比价单？',
          modalStyle: { wordBreak: 'break-all' },
        });
      } catch (e: any) {
        return;
      }
      const { planListNo } = renderData.value.find(
        (item) => item.id === selectedKeys.value[0]
      );
      const operParam = { planListNo, ...testval };
      try {
        const res: any = await generate(operParam);
        if (res.code === 200) {
          Message.success('生成成功');
          selectedKeys.value = [];
          const params = { planListNo };
          getData2(params);
        } else {
          Message.warning(res.message);
        }
      } catch (err: any) {
        console.log(err);
      } finally {
        isLoading.value = false;
      }
    } else if (typeChange === 'back') {
      if (selectedKeys.value.length !== 1) {
        Message.warning('请选择要退回的记录！');
        return;
      }
      try {
        await promiseModal.confirm({
          title: '退回',
          content: '您确定要将当前所选的数据退回？',
          modalStyle: { wordBreak: 'break-all' },
        });
      } catch (e: any) {
        return;
      }
      const { planListNo } = renderData.value.find(
        (item) => item.id === selectedKeys.value[0]
      );
      const operParam = { planListNo, ...testval };
      try {
        const res: any = await sheetReturn([operParam]);
        if (res.code === 200) {
          Message.success('退回成功');
          renderData2.value = [];
          getData(pageRef.value.getStatus());
          total2.value = 0;
          selectedKeys.value = [];
        } else {
          Message.warning(res.message);
        }
      } catch (err: any) {
        console.log(err);
      } finally {
        isLoading.value = false;
      }
    } else if (typeChange === 'approval') {
      if (selectedKeys.value.length < 1) {
        Message.warning('请选择要审批的记录！');
        return;
      }
      try {
        await promiseModal.confirm({
          title: '提交审批',
          content: '您确定要提交审批当前所选的数据！',
          modalStyle: { wordBreak: 'break-all' },
        });
      } catch (e: any) {
        return;
      }
      const operParam = selectedKeys.value.map((item) => {
        const record = renderData.value.find((val) => val.id === item);
        return { ...record };
      });
      try {
        const res: any = await approved(operParam);
        if (res.code === 200) {
          Message.success('审批成功');
          renderData2.value = [];
          getData(pageRef.value.getStatus());
          total2.value = 0;
          selectedKeys.value = [];
        } else {
          Message.warning(res.message);
        }
      } catch (err: any) {
        console.log(err);
      } finally {
        isLoading.value = false;
      }
    }
  };
  const handleAttachment = async (record: any) => {
    const { data } = await getPlanFileListByplanListNo(record.planListNo);
    attachmentList.value = data;
    console.log(data);
  };
  const rowClick = async (val: any) => {
    console.log(val);
    planListNoStroage.value = val.planListNo;
    const params = { planListNo: val.planListNo };
    getData2(params);
  };
  const handleDown = (val: any) => {
    window.open(val.url);
  };
  const handleDel = async (val: any, index: any) => {
    const { data } = await delPlanFile([val.id]);
    if (data) {
      attachmentList.value.splice(index, 1);
      Message.success('删除成功');
    }
  };
  const getData2 = async (form = {}) => {
    isLoading2.value = true;
    selectedKeys2.value = [];
    const queryPagination = table2.value.getStatus();
    const params = { ...form, ...queryPagination };
    try {
      const res: any = await page(params);
      if (res.code === 200) {
        renderData2.value = res.data.list;
        total2.value = res.data.total;
        console.log(res);
      }
    } catch (err: any) {
      console.log(err);
    } finally {
      isLoading2.value = false;
    }
  };
  const putSheet = async () => {
    try {
      const res: any = await putCompare(formSheet.value);
      if (res.code === 200) {
        Message.success('修改成功');
        visible.value = false;
        getData(pageRef.value.getStatus());
        getData2({ planListNo: planListNoStroage.value });
      }
      return true;
    } catch {
      return false;
    }
  };
  const editSheet = (record: any, index: any) => {
    console.log(record, index);
    formSheet.value = {};
    formSheet.value = { ...record };
    visible.value = true;
  };

  const initData = async () => {
    btnList.value = getBtnList(
      activeTab.value,
      activeRadio.value,
      // selectedKeys.value,
      selsectlist.value
    );
    rowBtnList.value = getRowBtnList(activeTab.value, activeRadio.value);

    // console.log('rowBtnList.value', rowBtnList.value);
  };

  const pageChange = async () => {
    getData2({ planListNo: planListNoStroage.value });
  };

  const pageSizeChange = async () => {
    getData2({ planListNo: planListNoStroage.value });
  };

  const initColumns = (data: any[]) => {
    columns.value = lodash.cloneDeep(data);
    allColumns.value = lodash.cloneDeep(data);
  };

  watch(activeTab, () => {
    // console.log(newval, oldval, 'activeTab');
    activeRadio.value = '1';
    initData();
  });

  watch(activeRadio, () => {
    // console.log(newval, oldval, 'activeRadio');
    initData();
  });

  onMounted(() => {
    activeTab.value = '1';
    activeRadio.value = '1';
    initData();
  });
</script>

<style lang="less" scoped>
  .page-con {
    height: 100%;
    padding: 20px;
    background-color: #fff;
  }

  .radio-ara {
    display: flex;
    justify-content: space-between;
    width: 17.5%;
  }

  .edit-form {
    ::v-deep .arco-form-item {
      background: #fff;

      &:focus-within {
        border-color: #165dff;
      }

      .arco-form-item-wrapper-col {
        border: 1px solid #d9dee7;
        border-radius: 3px;
      }

      .arco-picker-size-medium {
        width: 100%;
      }

      .arco-select-view-size-medium {
        width: 100% !important;
      }

      .arco-input-wrapper,
      .arco-picker,
      .arco-select-view-single {
        padding: 0 8px;
        background-color: transparent;
        border-color: transparent;
      }
    }
  }
</style>
: { id: any; }: any
